<template>
  <div class="recentplay">
  <div class="song-table">
      <el-table style="width: 100%" :data="songs" empty-text="没有找到下载记录哦" @row-dblclick="playMusic"
          :row-class-name="tableRowClassName">
          <!-- 索引或者小喇叭 -->
          <el-table-column width="50">
              <template v-slot="scope">
                  <span class="iconfont" :class="isPlaying? ' icon-voice' : 'icon-jingyin_laba'"
                      v-if="scope.row.id === nowSongDetail.id"></span>
                  <!-- <span v-else>{{ scope.row.index | formatIndex }}</span> -->
              </template>
          </el-table-column>
          <!-- 操作按钮 -->
          <el-table-column width="120">
              <template v-slot="scope">
                  <div class="operation">
                      <span
                          @click="likeSong(scope.row)"
                          :class="likeSongIds.indexOf(scope.row.id)!== -1? 'iconfont icon-xihuan2' : 'iconfont icon-xihuan'"
                          :title="likeSongIds.indexOf(scope.row.id)!== -1? '取消喜欢' : '喜欢'"
                      >
                      </span>
                      <span class="iconfont icon-xiazai" @click="downloadCurrentMusic(scope.row)" title="下载"></span>
                      <span class="iconfont icon-tianjiadaobofangliebiao1-copy" @click="addSong(scope.row)" title="添加到播放列表"></span>
                  </div>
              </template>
          </el-table-column>
          <!-- 歌曲名和mv图标 -->
          <el-table-column prop="name" label="歌曲" width="300" :show-overflow-tooltip="true">
              <template v-slot="scope">
                  <div class="songname">
                      {{ scope.row.name }}
                      <i class="iconfont icon-vip" v-if="scope.row.fee === 1"></i>
                      <i class="iconfont icon-mv" v-if="scope.row.mv!== 0" @click="toMvDetail(scope.row.mv)"></i>
                  </div>
              </template>
          </el-table-column>
          <!-- 专辑名 -->
          <el-table-column prop="al.name" label="专辑" :show-overflow-tooltip="true">
              <template v-slot="scope">
                  <span @click="toAlbum(scope.row.al.id)" class="sthover">
                      {{ scope.row.al.name }}
                  </span>
              </template>
          </el-table-column>
          <!-- 歌手名 -->
          <el-table-column prop="ar[0].name" label="歌手" :show-overflow-tooltip="true">
              <template v-slot="scope">
                  <span @click="toSinger(scope.row.ar[0].id)" class="sthover">
                      {{ scope.row.ar[0].name }}
                  </span>
              </template>
          </el-table-column>
          <!-- 时长 -->
          <el-table-column prop="dt" label="时长">
              <template v-slot="scope">
               <span> {{ formatDuration(scope.row.dt) }}</span>
              </template>
         </el-table-column>
         <!-- 删除 -->
         <el-table-column >
              <template v-slot="scope">
                  <div class="operation">
                      <span class="iconfont icon-shanchu" @click="deleteCurrentMusic(scope.row)" title="删除"></span>                
                  </div>
              </template>
          </el-table-column>
      </el-table>
  </div>
</div>
</template>

<script setup>
import { getSongUrl, checkMusic, likeNowSong, getLikSongList } from "@/network/playmusic/playmusic.js";
import { useStore } from 'vuex';
import { ref, computed } from 'vue';
import {  formatDuration } from'@/common/formatDuration.js';

// 定义props接收父组件的数据
const props = defineProps({
  songs: {
      type: Array,
      default: () => {
          return [];
      }
  }
});

// 定义响应式数据
const islike = ref(false);
const currentIndex = ref([]);

// 获取store实例
const store = useStore();

// 计算属性
const isPlaying = computed(() => store.state.isPlaying);
const nowSongDetail = computed(() => store.state.nowSongDetail);
const isLogin = computed(() => store.state.isLogin);
const userInfo = computed(() => store.state.userInfo);
const userSongList = computed(() => store.state.userSongList);
const likeSongIds = computed(() => store.state.likeSongIds);

// 过滤器函数
function formatIndex(index) {
  if (index < 9) {
      return "0" + (index + 1);
  } else return index + 1;
}

// 如果没有用户的喜欢列表 就先获取
if (isLogin.value && likeSongIds.value.length === 0) {
  getUserLikSongs();
}

// 方法定义
async function playMusic(song) {
  try {
      // 先检查歌曲是否可用
      const checkRes = await checkMusic(song.id);
      // 获取歌曲url
      const urlRes = await getSongUrl(song.id);
      store.dispatch("saveSongUrl", urlRes.data.data[0].url);
      // 更新播放状态
      store.dispatch("changePlayState", true);
      // 提交vuex保存当前歌曲详情
      store.dispatch("saveSongDetail", song);
      // 提交vuex添加到播放列表
      store.dispatch("addPlayinglist", song);
  } catch (err) {
      ElMessage({
          message: "暂时无法播放，换首试试",
          type: "warning",
          center: true,
      });
  }
}

async function getUserLikSongs() {
  try {
      const res = await getLikSongList(store.state.userInfo.value.userId);
      if (Array.isArray(res.data.ids) && res.data.ids.length!== 0) {
          store.dispatch("saveLikeSongIds", res.data.ids);
      }
  } catch (err) {
      console.error('获取用户喜欢歌曲列表失败：', err);
  }
}

async function likeSong(song) {
  // 先判断登录状态
  if (!isLogin.value) {
      ElMessage({
          type: "warning",
          message: "登录后才能收藏",
          showClose: true,
          center: true,
      });
      return;
  }
  // 判断传入参数是喜欢还是不喜欢
  let like = likeSongIds.value.indexOf(song.id)!== -1? false : true;
  // 如果是在用户喜欢的歌单点击的取消喜欢
  // 需要确认并从新获取用户歌单数据
  if (userSongList.value[0].id === store.$route.params.id) {
      try {
          const confirmResult = await store.$confirm("确定将选中歌曲从我喜欢的音乐中删除吗?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
              confirmButtonClass: "",
          });
          if (confirmResult) {
              // 如果删除的话就调接口
              await likeNowSongBy(song, like);
              // 更新歌单
              store.$emit("updateSonglist");
          }
      } catch (err) {
          err;
      }
      return;
  }
  // 否则不在用户喜欢的歌单 直接调接口
  else {
      await likeNowSongBy(song, like);
  }
}

/* 网络请求 喜欢/不喜欢歌曲 */
const likeNowSongBy = async (song, like) => {
  try {
      await likeNowSong(song.id, like);
      // 重新获取用户喜欢的歌曲id列表
      await getUserLikSongs();
      if (like) {
          store.$message.success('已添加到我喜欢的音乐');
          islike.value = true;
      } else {
          store.$message.success('取消喜欢成功');
          islike.value = false;
      }
  } catch (err) {
      store.$message.warning('操作失败,请重试');
  }
};

const downloadCurrentMusic = async (song) => {
  try {
    // 检查是否有版权
    await checkMusic(song.id);

    // 获取歌曲 URL
    const res = await getSongUrl(song.id);
    console.log('歌曲 URL:', res);  // 输出响应数据
    const songUrl = res.data.data[0].url;

    // 如果没有 URL，可能是获取失败
    if (!songUrl) {
      throw new Error('歌曲 URL 获取失败');
    }

    // 构建下载歌曲信息
    const downloadMusicInfo = {
      url: songUrl,
      name: `${song.name} - ${song.ar[0].name}`,
    };

    // 提交到 Vuex
    store.commit('updateDownloadMusicInfo', downloadMusicInfo);
  } catch (err) {
    // 异常处理
    console.error(err);
    store.state.$message({
      message: '暂无版权，无法下载',
      type: 'warning',
      center: true,
    });
  }
};

// 点击添加按钮
function addSong(song) {
  // 提交vuex添加到播放列表
  store.dispatch("addPlayinglist", song);
  ElMessage({
      message: "已添加到播放列表",
      type: "success",
      center: true,
  });
}


  // 删除当前音乐播放记录
  function  deleteCurrentMusic(row) {
          const songId = row.id;
        store.dispatch('deleteHistory', songId);
        ElMessage({
      message: "已成功删除",
      type: "success",
      center: true,
  });
  }

    // 清空所有历史记录
    const deleteAllHistory = () => {
	store.dispatch('deleteAllHistory'); // 清空所有历史记录
	ElMessage({
      message: "已成功删除所有播放列表",
      type: "success",
      center: true,
  });
  };
// 点击歌手 去往歌手页面
function toSinger(id) {
  store.$router.push("/singerdetail/" + id);
}

// 去往专辑页面
function toAlbum(id) {
  store.$router.push("/albumdetail/" + id);
}

// 去往MV页面
function toMvDetail(id) {
  store.$router.push({
      name: "VideoDetail",
      params: { id, type: "mv" },
  });
}

// 实现当前播放歌曲行显示小喇叭
function tableRowClassName({ row, rowIndex }) {
  row.index = rowIndex;
  if (rowIndex % 2!== 0) {
      return "rowEven";
  }
}



</script>

<style lang="less" scoped>
.deleteoperation{
    position: relative;
    height: 40px;
}
.deleteAllHistory{
    background-color: var(--mycompColor);
   color: #fff;
    position: absolute;  /* 设置为绝对定位 */
     top: 0;           /* 设置距离顶部20px */
     right: 0; 
}
.operation {
	.icon-xihuan{
        font-size: 18px;
		color: #999;
		font-weight: 700;
    }
	.icon-tianjiadaobofangliebiao1-copy {
		font-size: 18px;
		color: #444;
		font-weight: 700;
	}
	.icon-xihuan2 {
		font-size: 18px;
		color: var(--themeColor);
	}
	.icon-xiazai {
        font-size: 18px;
		font-weight: 700;
		color: #999;
	}
	.icon-xihuan,
	.icon-xihuan2,
	.icon-xiazai {
		display: inline-block;
		width: 30px;
	}

	span {
		cursor: pointer;
		&:hover {
			color: var(--themeColor);
		}
	}
}
.icon-voice,
.icon-jingyin_laba {
	color: var(--themeColor);
}
.icon-mv {
	font-size: 22px;
	color: var(--themeColor);
	cursor: pointer;
	padding-left: 5px;
}
.icon-vip {
	color: var(--themeColor);
	font-size: 18px;
	font-weight: 400;
	padding-left: 5px;
}
.sthover:hover {
	display: inline-block;
	color: var(--themeColor);
	width: 100%;
	cursor: pointer;
}
.no {
	width: 100%;
	text-align: center;
	font-size: 24px;
	font-weight: 700;
}
.confirmButtonClass {
	background-color: var(--themeColor) !important;
	border-color: var(--themeColor) !important;
}
</style>
